package com.yhos.platform.oopston.core.aop;

import com.yhos.platform.oopston.core.base.PageResponse;
import com.yhos.platform.oopston.core.base.Response;
import com.yhos.platform.oopston.core.constant.OperatorConstant;
import com.yhos.platform.oopston.core.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;

public class ParamsReturnHandler {

    private static ParamsReturnHandler handler = null;

    private ParamsThreadLocalManager paramsThreadLocalManager = ParamsThreadLocalManager.getInstance();

    public static synchronized ParamsReturnHandler getInstance() {
        if (handler == null) {
            handler = new ParamsReturnHandler();
        }
        return handler;
    }

    public void doReturnHandler(Object returnObj) throws Exception {
        String requestUUID = "";
        if (paramsThreadLocalManager.getParams().getAllRequestParamsMap().get(OperatorConstant.FROM_SOURCE_ID) != null) {
            requestUUID = (String) paramsThreadLocalManager.getParams().getAllRequestParamsMap().get(OperatorConstant.FROM_SOURCE_ID);
        }

        if (returnObj instanceof Response) {
            if (StringUtils.isBlank(((Response) returnObj).getSuccess())) {
                ((Response) returnObj).setSuccess(OperatorConstant.RETURN_SUCCESS);
            }
            if (StringUtils.isBlank(((Response) returnObj).getMsg())) {
                ((Response) returnObj).setMsg(OperatorConstant.OPERATOR_SUCCESS);
            }
            ((Response) returnObj).setResponseTime(DateUtils.dateToString(new Date()));
            ((Response) returnObj).setRequestUUID(requestUUID);
        }

        if (returnObj instanceof PageResponse) {
            if (StringUtils.isBlank(((PageResponse) returnObj).getSuccess())) {
                ((PageResponse) returnObj).setSuccess(OperatorConstant.RETURN_SUCCESS);
            }
            if (StringUtils.isBlank(((PageResponse) returnObj).getMsg())) {
                ((PageResponse) returnObj).setMsg(OperatorConstant.OPERATOR_SUCCESS);
            }
            ((PageResponse) returnObj).setResponseTime(DateUtils.dateToString(new Date()));
            ((PageResponse) returnObj).setRequestUUID(requestUUID);
        }
    }

}